package vs_a1;

import java.util.ArrayList;

/**
 * Delivery Queue:
 * Queue to store all messages received by the Server up to a maximum of max Messages.
 * @author Jan Quenzel
 * @author Rico Flaegel
 */
public class DeliveryQueue extends ArrayList<Message> {
	
	private static final long serialVersionUID = 1L;
	private int maxMessages;
	/**
	 * Constructor
	 * @param maxMessages maximal size of the Queue.
	 */
	DeliveryQueue(int maxMessages) {
		this.maxMessages = maxMessages;
	}

	/**
	 * Get the count of maximal messages.
	 * @return maximum count of messages at a time
	 */
	public synchronized int getMaxMessages() {
		return this.maxMessages;
	}

	/**
	 * Sets the number of maximum messages of the Server.
	 * @param maxMessageCount 
	 * @return true if it was successful, else false. 
	 */
	public synchronized boolean setMaxMessages(int maxMessageCount) {
		if (maxMessageCount > 0) {
			this.maxMessages = maxMessageCount;
			removeOverhead();
			return true;
		}
		return false;
	}
	
	/**
	 * removes all Messages above the max Message size.
	 */
	private synchronized void removeOverhead(){
		while (size() >= maxMessages) {
			remove(0);
		}
	}

	/**
	 * Gets the next Message to a client.
	 * @param clientID the ID of the client
	 * @param c all information about a given client.
	 * @return the next found Message or null if got none.
	 */
	public Message getMessageToClientID(String clientID, ClientType c) {
		if (clientID != null && !clientID.equals("") ) {
			for ( Message m : this ) {
				if ((!m.getClientID().equals(clientID))
						&& (!c.contains(m.getMessageID()))) {
					return m;
				}
			}
		}
		return null;
	}

	@Override
	public synchronized boolean add(Message m) {
		removeOverhead();
		return super.add(m);
	}

	@Override
	public String toString() {
		StringBuilder resu = new StringBuilder("DeliveryQueue:\n");
		for (Message m : this) {
			resu.append(m.toString() + "\n");
		}
		return resu.toString();
	}
}
